import React, { useState, useEffect } from 'react';
import { API_CONFIG } from '../config/constants';

const NetworkStatus = ({ onRetry }) => {
    const [networkStatus, setNetworkStatus] = useState('checking');
    const [errorDetails, setErrorDetails] = useState(null);

    const checkNetworkStatus = async () => {
        setNetworkStatus('checking');
        setErrorDetails(null);

        try {
            // 简单的网络连接测试
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 5000);

            const response = await fetch(API_CONFIG.BASE_URL, {
                method: 'GET',
                signal: controller.signal,
                mode: 'no-cors' // 避免CORS问题
            });

            clearTimeout(timeoutId);
            setNetworkStatus('connected');
        } catch (error) {
            let errorMessage = '网络连接失败';
            let suggestions = [];

            if (error.name === 'AbortError') {
                errorMessage = '连接超时';
                suggestions.push('检查网络连接是否正常');
                suggestions.push('确认服务器是否正在运行');
            } else if (error.message.includes('Failed to fetch')) {
                errorMessage = '无法连接到服务器';
                suggestions.push('确认服务器地址是否正确: ' + API_CONFIG.BASE_URL);
                suggestions.push('检查防火墙设置');
                suggestions.push('确认服务器是否启动');
            }

            setNetworkStatus('disconnected');
            setErrorDetails({ message: errorMessage, suggestions });
        }
    };

    useEffect(() => {
        checkNetworkStatus();
    }, []);

    if (networkStatus === 'checking') {
        return (
            <div className="network-status checking">
                <div className="status-icon">🔍</div>
                <div className="status-message">正在检查网络连接...</div>
            </div>
        );
    }

    if (networkStatus === 'connected') {
        return null; // 连接正常时不显示
    }

    return (
        <div className="network-status error">
            <div className="status-header">
                <div className="status-icon">⚠️</div>
                <div className="status-title">网络连接问题</div>
            </div>

            <div className="error-details">
                <p className="error-message">{errorDetails?.message}</p>

                {errorDetails?.suggestions && (
                    <div className="suggestions">
                        <p><strong>建议解决方案:</strong></p>
                        <ul>
                            {errorDetails.suggestions.map((suggestion, index) => (
                                <li key={index}>{suggestion}</li>
                            ))}
                        </ul>
                    </div>
                )}
            </div>

            <div className="status-actions">
                <button
                    className="retry-btn"
                    onClick={() => {
                        checkNetworkStatus();
                        if (onRetry) onRetry();
                    }}
                >
                    重试连接
                </button>
            </div>
        </div>
    );
};

export default NetworkStatus;